HTTPS = "https:"
BODY = $('body')

KV = idbKeyval
DB =
  CITY : new KV.Store("xvc","city")

fetch = =>
  keyword = _keyword()
  [city,page] = await KV.get(keyword, DB.CITY)
  url = _search_url(keyword,city,page)
  if url[..-SEARCH.length-1] != decodeURIComponent(location.pathname)
    _go url
    return

  next = $(".page .next")
  if next[0]
    page = page + 1
  else
    page = 1
    city = CITY_ID[CITY_ID.indexOf(city)+1]
    if not city
      alert '导出成功'
      return


dump = (a , tip)=>
  keyword = decodeURIComponent(location.pathname.split("/")[4][2..])
  [city,page] = (await KV.get(keyword, DB.CITY)) or [CITY_ID[0], 1]
  total = CITY_ID.length + 1
  now = CITY_ID.indexOf(city)
  tip.text("#{now} / #{total}")
  url = "/search/keyword/#{city}/0_#{keyword}/o11p#{page}"
  r = $(await $.get(url))
  for i in r.find("#shop-all-list>ul>li")
    i = $(i)
    console.log(
      i.find('h4').text()
      i.find('.tit a')[0].href
      i.find('.sml-rank-stars')[0].className.split(" ")[..]
    )
  await KV.set(
    keyword
    [city,page]
    DB.CITY
  )
        # keyword = _keyword()
        # now = await KV.get(keyword, DB.CITY)
        # if not now
        #   now = CITY_ID[0]
        # _search(keyword, now, 1)
        # process = $ '<span class=aCsv>导出中</a>'
        # $(@).append()

if location.protocol != HTTPS
  location.href = HTTPS + "//"+ location.href[7..]
else
  do =>
    search = location.search
    $ =>
      aCsv = $("<a class=aCsv>导出</a>")
      $(".search-bnt-panel").append(aCsv)
      aCsv.click ->
        aCsv.hide()
        process = $('<b class=tip>导出中 : <b></b></b>')
        aCsv.after process
        dump(@, process.find('b'))

      # await KV.set KEY.DUMPING, keyword
      # await KV.set KEY.CITY, CITY.join(" ")
      # await KV.set KEY.NOW, CITY[0]
      # location.href = _url keyword, 1
      # await KV
      # await KV
      # url = "http://www.dianping.com/search/keyword/2/#{keyword}/o11"
      # for i in CITY
      #   location.href = "https://"+location.host+"/"+i
      #   break
